import 'package:logger/logger.dart';

import '../../service/Path.dart';
import '../../util/ImSingleton.dart';
import '../dto/base/Req.dart';
import '../dto/base/Resp.dart';
import '../dto/business/RpcData.dart';
import '../exception/RpcException.dart';

class RpcService {

  var _logger = Logger(printer: PrettyPrinter(),);

  ///发送消息，并得到服务端的明确回复
  Future<T> sendDataAndOk<T>(ImPath path, Req req, Function fromJson, [int? timeout = 60]) async {
    String? seq = _createSeq();
    RpcData rpcData = RpcData.data(path.name, req, seq);
    RpcData? resultRpcData = await ImSingleton.getInstance()?.imWebSocket?.sendData(rpcData, fromJson, timeout);
    _logger.i("${path.name} success result : ${resultRpcData?.data}", );
    if (resultRpcData?.data is ExceptionResp) {
      var exceptionResp = resultRpcData?.data as ExceptionResp;
      throw RpcException(exceptionResp.errorMsg??'');
    }
    return resultRpcData?.data as T;
  }

  /// 只发送消息，并不需要服务端得到回复
  Future<T> sendDataNoOk<T>(ImPath path, Object data, [int? timeout = 60]) async {
    String? seq = _createSeq();
    RpcData rpcData = RpcData.data(path.name, data, seq);
    RpcData? resultRpcData = await ImSingleton.getInstance()?.imWebSocket?.sendData(rpcData, null, timeout);
    _logger.i("${path.name} success result : ${resultRpcData?.data}", );
    if (resultRpcData?.data is ExceptionResp) {
      var exceptionResp = resultRpcData?.data as ExceptionResp;
      throw RpcException(exceptionResp.errorMsg??'');
    }
    return resultRpcData?.data as T;
  }

  String _createSeq() {
    String? seq = ImSingleton.getInstance()?.seqCreator.create();
    return seq??'';
  }

}